package com.newgoldcurrency.activities.forgetpassword;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.SystemClock;
import android.view.View;

import androidx.activity.result.ActivityResultLauncher;
import androidx.activity.result.contract.ActivityResultContracts;
import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;

import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.newgoldcurrency.R;
import com.newgoldcurrency.databinding.ActivityForgetPasswordBinding;
import com.newgoldcurrency.utils.Tools;
import com.newgoldcurrency.utils.network.Network;
import com.newgoldcurrency.view.LoadingDialog;
import com.newgoldcurrency.view.VerificationCodeView;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Objects;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.Response;

public class ForgetPasswordVerifyActivity extends AppCompatActivity {
    private ActivityForgetPasswordBinding binding;
    private final List<Call> calls=new ArrayList<>();
    int time=60;
    Handler handler=new Handler();
    Runnable runnable=new Runnable() {
        @SuppressLint("SetTextI18n")
        @Override
        public void run() {
            if (time>0){
                time--;
                handler.postDelayed(this,1000);
                if (binding!=null)binding.forgetPasswordSend.setText(time+"s");
            }else {
                time=60;
                if (binding!=null)binding.forgetPasswordSend.setEnabled(true);
                if (binding!=null)binding.forgetPasswordSend.setText("Send");
            }
        }
    };
    private String verifyCode="";
    private long mClickTime;
    private LoadingDialog loading_dialog;
    private ActivityResultLauncher<Intent> launcher;

    private boolean checkDoubleClick() {
        boolean result= mClickTime < SystemClock.uptimeMillis() - 500;
        mClickTime = SystemClock.uptimeMillis();
        return result;
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityForgetPasswordBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        setResult(1);
        loading_dialog=new LoadingDialog(this);
        binding.forgetVerifyClose.setOnClickListener(v -> finish());
        binding.forgetPasswordVerify.setOnCodeFinishListener(new VerificationCodeView.OnCodeFinishListener() {
            @Override
            public void onTextChange(View view, String content) {
                if (content.length()==4){
                    binding.forgetVerifyNext.setBackgroundResource(R.drawable.bg_button);
                }else {
                    binding.forgetVerifyNext.setBackgroundResource(R.drawable.bg_button_disable);
                }
            }
            @Override
            public void onComplete(View view, String content) {
             verifyCode=content;
            }
        });
        binding.forgetPasswordSend.setOnClickListener(v -> {

            if (checkDoubleClick()) {
                if (loading_dialog != null && !loading_dialog.isShowing()) {
                    loading_dialog.show();
                    if (binding.forgetPasswordMail.getText().toString().equals("")){
                        Tools.toast(getString(R.string.please_input_email));
                        loading_dialog.dismiss();
                    }else {
                        if (Tools.isEmail(binding.forgetPasswordMail.getText().toString())){
                            HashMap<String, String> map=new HashMap<>();
                            map.put("mail",binding.forgetPasswordMail.getText().toString());
                            map.put("type","pwd");
                            Network.post(map, "user/getVerificationCode", call -> {
                                call.enqueue(new Callback() {
                                    @Override
                                    public void onFailure(@NonNull Call call, @NonNull IOException e) {
                                        runOnUiThread(() -> {
                                            e.printStackTrace();
                                            loading_dialog.dismiss();
                                        });
                                    }
                                    @Override
                                    public void onResponse(@NonNull Call call, @NonNull Response response) {
                                        runOnUiThread(() -> {
                                            loading_dialog.dismiss();
                                            try {
                                                String str= Objects.requireNonNull(response.body()).string();
                                                if (Tools.isJson(str)){
                                                    JsonObject jo = JsonParser.parseString(str).getAsJsonObject();
                                                    if (jo.get("message").getAsString().equals("Sent successfully")){
                                                        startDelay();
                                                    }else {
                                                        Tools.toast(jo.get("message").getAsString());
                                                    }
                                                }
                                            } catch (IOException e) {
                                                e.printStackTrace();
                                            }

                                        });
                                    }
                                });
                                calls.add(call);
                            });
                        }else {
                            loading_dialog.dismiss();
                            Tools.toast(getString(R.string.email_format_err));
                        }
                    }
                }
            }
        });
        binding.forgetVerifyNext.setOnClickListener(v ->{
            if (checkDoubleClick()){
                if (verifyCode.length()==4){
                    Intent intent=new Intent(ForgetPasswordVerifyActivity.this,ForgetPasswordSetPasswordActivity.class);
                    intent.putExtra("verifyCode",verifyCode);
                    intent.putExtra("mail",binding.forgetPasswordMail.getText().toString());
                    launcher.launch(intent);
                }else {
                    Tools.toast(getString(R.string.input_verify_code));
                }
            }
        });
        launcher=registerForActivityResult(new ActivityResultContracts.StartActivityForResult(), result -> {
            if (result.getResultCode()==2){
                setResult(3);
                finish();
            }
        });
    }

    private void startDelay() {
        handler.postDelayed(runnable,0);
        binding.forgetPasswordSend.setEnabled(false);
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        for (Call call :calls) {
            call.cancel();
        }
        handler.removeCallbacks(runnable);
        binding=null;
    }
}